package com.situ.userWeb.Service.Impl;

import java.util.ArrayList;
import java.util.List;

import com.situ.userWeb.Dao.IUserDao;
import com.situ.userWeb.Dao.Impl.UserDaoImpl;
import com.situ.userWeb.Service.IUserService;
import com.situ.userWeb.Util.JSONResult;
import com.situ.userWeb.entity.Department;
import com.situ.userWeb.entity.Role;
import com.situ.userWeb.entity.User;
import com.situ.userWeb.entity.UserRoleDepartment;

public class UserServiceImpl implements IUserService {
	private IUserDao userDao = new UserDaoImpl();

	@Override
	public List<UserRoleDepartment> selectAll() {
		List<UserRoleDepartment> list = userDao.selectAll();
		return list;
	}

	@Override
	public boolean delete(int id) {
		int count1 = userDao.delete(id);
		int count2 = userDao.deleteUR(id);
		return count1 == 1 ? true : false;
	}

	@Override
	public boolean insertUser(User user) {
		int count = userDao.insertUser(user);
		return count == 1 ? true : false;
	}

	@Override
	public int insertUR(int id, String[] roleId) {
		int count = 0;
		for (String string : roleId) {
			count = userDao.insertUR(id, Integer.parseInt(string));
			System.out.println(count);
		}
		return count;
	}

	@Override
	public ArrayList<Role> selectRole() {
		ArrayList<Role> list = userDao.selectRole();
		return list;
	}

	@Override
	public ArrayList<Department> selectDepartment() {
		ArrayList<Department> list = userDao.selectDepartment();
		return list;
	}

	@Override
	public JSONResult selectLayuiByPage(int page, int limit) {
		int offset = (page - 1) * limit;
		List<UserRoleDepartment> list = userDao.selectByPage(offset, limit);
		Integer totalCount = userDao.selectTotal();

		return JSONResult.success(list, totalCount);
	}

	@Override
	public User selectId(int userId) {
		User user = userDao.selectId(userId);
		return user;
	}

	@Override
	public boolean deleteAll(String[] ids) {
		int count = 0;
		for (String id : ids) {
			count += userDao.delete(Integer.parseInt(id));
		}
		return count == ids.length;
	}

	@Override
	public List<Integer> selectRoleIdByUser(Integer userId) {
		List<Integer> selectRoleId = userDao.selectRoleIdByUser(userId);
		return selectRoleId;
	}

	@Override
	public boolean update(User user) {
		int count = userDao.update(user);
		return count == 1;
	}

	@Override
	public boolean update(User user, Integer id, String[] roleId) {
		int count1 = userDao.update(user);
		int count2 = 0;
		userDao.deleteUR(id);
		for (String string : roleId) {
			count2 = userDao.insertUR(id, Integer.parseInt(string));
		}
		return count1 == 1;
	}

	@Override
	public boolean insert(User user, String[] roleId) {
		int id = userDao.insertUser(user);
		for (String string : roleId) {
			userDao.insertUR(id, Integer.parseInt(string));
		}
		return true;
	}
}
